package com.bwie.config;

import java.security.MessageDigest;

/**
 * MD5加密工具类
 * Created by progr on 2020/3/28.
 */
public class MD5Util {
    //盐
    static final String salt = "wertyuiopdfghjklfasfase";

    public final static String md5(String ss){//MD5加密算法
        String s = ss == null ? "":ss;//如果为空，则返回""
        char hexDigists[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d',
                'e','f'};//字典

        try {
            byte[] strTemp =s.getBytes();//获取二进制
            MessageDigest mdTemp =MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);//执行加密
            byte[] md = mdTemp.digest();//加密结果
            int j = md.length;//结果长度
            char str[] = new char[j*2];//字符数组
            int k = 0;
            for (int i = 0; i < j; i++) { //将二进制加密结果转化为字符
                byte byte0 = md[i];
                str[k++] = hexDigists[byte0 >>> 4 &0xf];
                str[k++] = hexDigists[byte0 & 0xf];

            }
            return new String(str);//输出加密后的字符
        } catch (Exception e) {
            // TODO Auto-generated catch block
            return null;
        }
    }
    //md5 单项加密 不可逆  原文相等 密文一定相等
    //  123456  ===>  e10adc3949ba59abbe56e057f20f883e
    public static void main(String[] args) {

        //原文
        String aa = "123456";
        //5c5ba116fc8b45c61d0b501672d4b7f8  2次
        //183759b405b98db090506da540e4c3f2  3次
        //String s = MD5Util.md5(MD5Util.md5(MD5Util.md5(aa+salt)+salt)+salt);
        String s = MD5Util.md5Code(aa,3);
        System.out.println(s);

    }
    //加盐加次数方法 递归算法
    public static String md5Code(String key,int i){
        //每次都先加盐
        if( i == 1){
            //加密一次
            return MD5Util.md5(key+salt);
        }
        return MD5Util.md5( MD5Util.md5Code(key,i-1)+salt);

    }

}
